//import("consts.js");
//import("vars.js");
//import("functions.js");
//import("rem.js");
//import("utils.js");
//import("posFixed.js");

async function sleep(handler, timeout = 1) {
    await setTimeout(handler, timeout);
}

function throttle(func, wait) {
    let lastTime = null;
    let timeout;
    return function() {
        let context = this;
        let now = new Date();
        // 如果上次执行的时间和这次触发的时间大于一个执行周期，则执行
        if (now - lastTime - wait > 0) {
            // 如果之前有了定时任务则清除
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context, arguments);
            lastTime = now;
        } else if (!timeout) {
            timeout = setTimeout(() => {
                // 改变执行上下文环境
                func.apply(context, arguments);
            }, wait);
        }
    };
}
function debounce(func, wait) {
    let lastTime = null;
    let timeout;
    return function() {
        let context = this;
        let now = new Date();
        // 判定不是一次抖动
        if (now - lastTime - wait > 0) {
            setTimeout(() => {
                func.apply(context, arguments);
            }, wait);
        } else {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            timeout = setTimeout(() => {
                func.apply(context, arguments);
            }, wait);
        }
        // 注意这里lastTime是上次的触发时间
        lastTime = now;
    }
}

function loadMoreMulti(conf) {
    if(!Array.isArray(conf)){
        return false;
    }
    let $clickEl = $('.loadmore-click-tab-js');
    let index = 0;
    let data = conf[index];
    let lock = function(dropload){
        // 锁定
        dropload.lock();
        dropload.noData();
    };

    let unLock = function(dropload){
        // 解锁
        dropload.unlock();
        dropload.noData(false);
    };
    conf.forEach((item)=>{
        item.loadEnd = false;
        item.params.page = 1;
    });

    let dropload = $('.loadmore-tab-js').dropload({
        scrollArea : window,
        loadDownFn : function(me){
            if(data.loadEnd){
                lock(me);
                me.resetload();
                return false;
            }
            if(!$clickEl.eq(index).hasClass('active')){
                lock(me);
                me.resetload();
                return false;
            }
            data.params.page++;
            $.ajax({
                type: 'GET',
                url: data.url,
                data: data.params,
                success: function (res) {
                    if(!$(res).find(data.el).children().length){
                        lock(me);
                        me.resetload();
                        data.loadEnd = true;
                        return false;
                    }
                    $(data.el).append($(res).find(data.el).html());
                    typeof data.options.fnSuccess === 'function' && data.options.fnSuccess(res);
                    setTimeout( ()=> {
                        // 每次数据加载完，必须重置
                        me.resetload();
                    })
                },
                error: function () {
                    data.params.page--;
                    me.resetload();
                }
            });
        }
    });

    $clickEl.on('click', function () {
        index = $clickEl.index(this);
        data = conf[index];
        if(!data){
            index = $clickEl.length - index;
            data = conf[index];
        }
        if(data.loadEnd){
            lock(dropload);
        }else{
            unLock(dropload);
        }
        // 重置
        dropload.resetload();
    });
    
}

function loadMore(contentEle, url, params = {}, options = {}) {
    let $el = $(contentEle);
    let defOptions = {
        fnBefore(v){
            return v;
        },
        fnSuccess(){},
    };
    options = Object.assign({},defOptions, options);
    let defParams = {
        page: 2,
        per_page: 10,
    };
    params = Object.assign({}, defParams,params);
    return $el.parent().dropload({
        scrollArea : window,
        loadDownFn : function(me){
            params = options.fnBefore(params,me);
            $.ajax({
                type: 'GET',
                url,
                data: params,
                success: function (res) {
                    if(!$(res).find(contentEle).children().length){
                        me.lock();
                        me.noData();
                        me.resetload();
                        return false;
                    }
                    params.page++;
                    $el.append($(res).find(contentEle).html());
                    typeof options.fnSuccess === 'function' && options.fnSuccess(res);
                    setTimeout( ()=> {
                        // 每次数据加载完，必须重置
                        me.resetload();
                    })
                },
                error: function (e) {
                    me.resetload();
                }
            });
        }
    });
}

function multiLoadMore(arr) {

}


var swiperDefaultConf = {
    autoplay: {
        delay: 3000,
        stopOnLastSlide: false,
        disableOnInteraction: true,
    },
    pagination :{
        clickable :true,
    },
    // 如果需要分页器
    loop: true
};

function initSwiper(container, confObj = {}) {
    var $container = $(container),
        conf = {},
        pagination = {};

    confObj.pagination = confObj.pagination || {};
    Object.assign(pagination, swiperDefaultConf.pagination, confObj.pagination);
    Object.assign(conf, swiperDefaultConf, confObj);
    pagination.el = `${container} .swiper-pagination`;
    conf.pagination = pagination;

    if (!$container.length) {
        return false;
    }

    var mySwiper = new Swiper(container, conf);
    $(container).mouseleave(function () {
        mySwiper.autoplay.start();
    });

    return mySwiper;
}


function scrollUp(){
    if(!$(document).scrollTop()){
        $('.fix-top-menu-list').addClass('to-top');
        $('.fix-bottom-js').addClass('to-bottom');
    }else{
        $('.fix-top-menu-list').removeClass('to-top');
        $('.fix-bottom-js').removeClass('to-bottom');
    }
}

$(function () {

    $('.tab-list-js a').on('click', function () {
        $(this).tab('show');
    });

    $('.tab-list-js').each(function () {
        $(this).find('li').on('click', function () {
            let index = $(this).index();
            $('.tab-list-js').each(function () {
                $(this).find('li').removeClass('active').eq(index).addClass('active');
            });

            // a 不能进行锚点跳转 不知道为什么
            if($($(this).find('a').attr('href')).length){
                let top = Math.ceil($($(this).find('a').attr('href')).offset().top) - $(this).height();
                $(window).scrollTop(top);
            }
        });
    });

    scrollUp();
    $(window).on('scroll', function () {
        scrollUp();
    });

    {
        $('.img-gallery').each((index, item)=>{
            let $el = $(item);
            let childTagName = '';
            try{
                childTagName = $el.children().first().get(0).tagName;
            }catch(e){
            }
            if(childTagName){
                $el.magnificPopup({
                    delegate: childTagName,
                    type: 'image',
                    closeOnContentClick: false,
                    closeBtnInside: false,
                    mainClass: 'mfp-with-zoom mfp-img-mobile',
                    image: {
                        verticalFit: true,
                        titleSrc: function(item) {
                        }
                    },
                    gallery: {
                        enabled: true
                    },
                    zoom: {
                        enabled: true,
                        duration: 300, // don't foget to change the duration also in CSS
                        opener: function(element) {
                            return element.find('img');
                        }
                    }

                })
            }
        });
    }
});

class ScrollInView{
    constructor(el, options = {}){
        this.$el = $(el);
        this.$elChildren = this.$el.find('a');
        this.$win = $(window);
        this.pageHeight = this.$win.height();
        this.bodyHeight = $('body').height();
        this.elHeight = this.$el.height();
        this.keys = [];
        this.defOptions = {
            offset: 0,
        };
        this.options = Object.assign({},this.defOptions, options);
        this.data = [];
        this.scrollCb = this._scrollCb.bind(this);
        this.init();
    }
    init(){
        this.initBefore();
        this.initData();
        this.initEle();
        this.initEvent();
    }
    initBefore(){
        this.$elChildren.each((index, item)=>{
            let key = $(item).attr('href');
            this.keys.push(key);
        });
    }
    initEle(){
        this.$el.children().on('click', function () {
            $(this).addClass('active').siblings().removeClass('active');
        });
        this.$elChildren.each((index, item)=>{
            let $targetEl = this.data[index].$el;
            $(item).attr({
                href: 'javascript:;'
            }).on('click', ()=>{
                $('html, body').animate({
                    scrollTop: $targetEl.offset().top - this.elHeight - this.options.offset
                }, 'fast');
            });
        })
    }
    initData(){
        let data = [];
        this.$elChildren.each((index)=>{
            let key = this.keys[index];
            let obj = {
                el: key,
                $el: $(key),
            };
            data.push(obj);
        });
        this.data = [...data];
    }
    initEvent(){
        this.$win.on('scroll', this.scrollCb);
    }

    _scrollCb(){
        let index = 0;
        let scrollTop = this.$win.scrollTop();
        let length = this.data.length;
        //检测滚动到底部
        if(scrollTop + this.pageHeight >= this.bodyHeight){
            index = length - 1;
        }else{
            for(let i = length - 1;i >= 0; i--){
                if(scrollTop + this.elHeight + this.options.offset + 1 > this.data[i].$el.offset().top){
                    index = i;
                    break;
                }
            }
        }
        this.$el.children().removeClass('active').eq(index).addClass('active');
    }

    destroy(){
        this.$win.off('scroll', this.scrollCb);
    }
}


class BottomPopup{
    constructor(el, options = {}){
        this.$el = $(el);
        this.$maskEl = $('.bottom-popup__mask');
        this.defOptions = {
            onShow(){},
            onHide(){},
        };
        this.options = Object.assign({},this.defOptions, options);
        this.init();
    }

    init(){
        this.initEvent();
    }

    initEvent(){
        this.$maskEl.on('click', ()=>{
            this.hide();
        });
        this.$el.find('.close-bottom-popup').on('click', ()=>{
            this.hide();
        });
    }

    show(){
        this.$el.removeClass('hidden');
        this.$maskEl.removeClass('hidden');
        setTimeout(()=>{
            this.$el.addClass('active').one('transitionend',  ()=> {
                this.options.onShow();
            });
            this.$maskEl.addClass('active');
        });
    }

    hide(){
        this.options.onHide();
        this.$maskEl.removeClass('active');
        this.$el.removeClass('active').one('transitionend',  ()=> {
            this.$el.addClass('hidden');
            this.$maskEl.addClass('hidden');
        });
    }
}



